<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\LevelModel;
use app\admin\model\UsersModel;
use app\admin\model\SignModel;
use app\admin\model\AccountLogModel;

class Users extends Base
{
    //用户列表
    public function index()
    {
        if(IS_AJAX){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                $where['mobile'] = $param['searchText'];
            }

            $user = new UsersModel();
            $selectResult = $user->getUsersByWhere($where, $offset, $limit);


            $status = config('users_status');

            $level = new LevelModel();
            $usersLevel = $level->getLevel();

            $usersLevel = convert_arr_key($usersLevel,'level_id');


            // 拼装参数
            foreach($selectResult as $key=>$vo){

                $selectResult[$key]['last_login'] = date('Y-m-d H:i:s', $vo['last_login']);
                $selectResult[$key]['reg_time'] = date('Y-m-d H:i:s', $vo['reg_time']);
                $selectResult[$key]['status'] = $status[$vo['is_lock']];
                $selectResult[$key]['level'] = $usersLevel[$vo['level']]['level_name'];
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['user_id']));
            }



            $return['total'] = $user->getAllUsers($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        return $this->fetch();
    }

    // 添加用户
    public function userAdd()
    {
        if(IS_POST){

            $param = input('post.');
            $param['password'] = encrypt($param['password']);
            $param['head_pic'] = '/static/admin/images/profile_small.jpg'; // 默认头像
            $user = new UsersModel();
            $flag = $user->insertUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $level = new LevelModel();
        $this->assign([
            'level' => $level->getLevel(),
            'status' => config('users_status')
        ]);

        return $this->fetch();
    }

    // 编辑用户
    public function userEdit()
    {
        $user = new UsersModel();

        if(IS_POST){

            $param = input('post.');

            if(empty($param['password'])){
                unset($param['password']);
            }else{
                $param['password'] = encrypt($param['password']);
            }
            $flag = $user->editUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $id = input('param.id');
        $level = new LevelModel();
        $this->assign([
            'user' => $user->getOneUser($id),
            'status' => config('users_status'),
            'level' => $level->getLevel()
        ]);
        return $this->fetch();
    }

    //资金
    public function accountLog(){

        if(IS_AJAX){
            $param = input('param.');

            $limit = $param['pageSize'];

            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = ['user_id'=>$param['id']];

            if (!empty($param['searchText'])) {
                $where['mobile'] = $param['searchText'];
            }

            $account_log = new AccountLogModel();
            $selectResult = $account_log->getAccountLogModelByWhere($where, $offset, $limit);

            // 拼装参数
            foreach($selectResult as $key=>$vo){

                $selectResult[$key]['change_time'] = date('Y-m-d H:i:s', $vo['change_time']);
                // $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['user_id']));
            }



            $return['total'] = $account_log->getAllAccountLog($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }
        $this->assign([
            'id' => input('id'),
        ]);
        return $this->fetch();
    }

    public function accountLogUpdate(){
        $id = input('id/d');
        $users = new UsersModel();
        $selectResult = $users->getOneUser($id);

        if(IS_POST){
            $param = input('param.');

            if ($param['point_act_type']!=1 and $param['pay_points']>$selectResult['pay_points']) {
                return json(msg(0, '', '积分不足'));
            }


            if ($param['money_act_type']!=1 and $param['user_money']>$selectResult['user_money']) {
                return json(msg(0, '', '余额不足'));
            }
          
            if ($param['point_act_type']==1) {
                db('users')->where(['user_id'=>$param['id']])->setInc('score',$param['pay_points']);
            }else{
                db('users')->where(['user_id'=>$param['id']])->setDec('score',$param['pay_points']);
                $param['pay_points']= -$param['pay_points'];
            }

            if ($param['money_act_type']==1) {
                db('users')->where(['user_id'=>$param['id']])->setInc('score',$param['user_money']);
            }else{
                db('users')->where(['user_id'=>$param['id']])->setDec('score',$param['user_money']);
                $param['user_money']= -$param['user_money'];
            }

            accountLog($param['id'], $param['user_money'],$param['pay_points'], $desc = $param['desc']);

            return json(msg(0,'' , '更新成功'));

        }
        $this->assign([
            'user' => $selectResult
        ]);
        return $this->fetch();
    }


    // 删除用户
    public function userDel()
    {
        $id = input('param.id');

        $role = new UserModel();
        $flag = $role->delUser($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }


    /**
     * 签到列表
     * @date 2017/09/28
     */
    public function sign_list() {       
        if(IS_AJAX){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['mobile'])) {
                $where['mobile'] = $param['mobile'];
            }

            $sign = new SignModel();
            $selectResult = $sign->getDataByWhere($where, $offset, $limit);

            // 拼装参数
            foreach($selectResult as $key=>$vo){

               
            }



            $return['total'] = $sign->getCount($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }
        return $this->fetch();
    }
    
    
    /**
     * 会员签到 ajax
     * @date 2017/09/28
     */
    public function ajaxSignList() {
    $mobile = input('post.mobile','');
    $map = '1=1';
    if ($mobile) {
       //根据手机号获取用户信息
        $user_id = db('users')->where('mobile',$mobile)->getField('user_id');
        if ($user_id) {
            $map .= 'and user_id='.$user_id;
        }
        
    }
        
    $UserSign  = new UserSign();
    $count = $UserSign->where($map)->count();
    $page = new Page($count);
    $list  = $UserSign->with('users')->where($map)->order('id desc')->limit($page->firstRow.','.$page->listRows)->select();
    $this->assign('pager',$page);
    $this->assign('page',$page->show());
    $this->assign('list',$list);
    return $this->fetch();
    }
    
    /**
     * 签到规则设置 
     * @date 2017/09/28
     */
    public function sign_rule() {

    if (IS_POST) {
        $param = input('post.');
        unset($param['form_submit']);
        tpCache('sign',$param);
        $this->success("操作成功",url('User/sign_rule'));
    }
    $this->assign('config',tpCache('sign'));//当前配置项
    return $this->fetch();
    }





    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '编辑' => [
                'auth' => 'users/useredit',
                'href' => url('users/userEdit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '资金' => [
                'auth' => 'users/accountlog',
                'href' => url('users/accountLog', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [
                'auth' => 'users/userdel',
                'href' => "javascript:userDel(" .$id .")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];
    }
}
